import { getApi, getHeader, successHandler, failHandler, startShowLoading } from './config';

/**
 * 执行器
 * @returns
 */
const handler = run => {
    return new Promise((resolve, reject) => {
        run(resolve, reject)();
    });
};

/**
 * http请求函数
 * @param {请求名称} name
 * @param {接口入参} data
 * @description
 *  pem: Boolean 是否由系统拦截处理错误，默认为false
 *  sld: Boolean 是否显示请求loading，默认为true
 *  lmt: Number  如何处理429响应，0 系统拦截(默认)；1 页面自行处理；-1 无任何处理；2 跳转到空态页面; 通常用于处理服务端限流场景
 */
const request = (name = '', data = {}) => {
    const { url, method = 'post', pem = false, sld = true, lmt = 0, timeout = 3000 } = getApi(name);

    const header = getHeader();

    const req = {
        url,
        method,
        header,
        pem,
        sld,
        lmt,
        timeout
    };

    /**
     * 请求函数
     * @param {*} resolve
     * @param {*} reject
     * @returns
     */
    const run = (resolve, reject) => {
        return () => {
            startShowLoading(sld);
            uni.request({
                url,
                header,
                method,
                data,
                timeout,
                success(res) {
                    successHandler(req, res, resolve, reject);
                },
                fail: err => {
                    failHandler(err);
                }
            });
        };
    };
    return handler(run);
};

export default request;
